package com.hzncc.scaffold.controller.Rear.OnePlusX;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Bo.GetTrainerListBo;
import com.hzncc.scaffold.entity.Other.*;
import com.hzncc.scaffold.entity.Vo.*;
import com.hzncc.scaffold.mapper.OneplusxtrainingMapper;
import com.hzncc.scaffold.mapper.TrainerapplyMapper;
import com.hzncc.scaffold.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: DrunkBear
 * @Date: 2022-05-24 18:10
 * @Description: null
 */
@Api(tags = "1+X管理-培训管理")
@RequestMapping("/manage/onePlusXTraining")
@RestController
public class OnePlusXTrainingController {

    @Autowired
    OneplusxtrainingService oneplusxtrainingService;

    @Autowired
    OneplusxtrainingMapper oneplusxtrainingMapper;

    @Autowired
    InvigilatorconfirmService invigilatorconfirmService;
    @Autowired
    TrainerapplyMapper trainerapplyMapper;

    @Autowired
    TrainerapplyService trainerapplyService;

    @Autowired
    CertificateService certificateService;

    @Autowired
    CertnumService certnumService;


    @GetMapping("/list")
    @ApiOperation("获取培训管理列表")
    public ResultT list(Integer pageNum, Integer pageSize, String keyword, Integer status) {
        QueryWrapper<OnePlusXTrainingListVo> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(keyword)) {
            qw.like("title", keyword);
        }
        qw.orderByDesc("stayAtTop");
        qw.orderByDesc("sortTime");

        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<OnePlusXTrainingListVo> onePlusXTrainingListVos = oneplusxtrainingMapper.listVo(qw);

        for (OnePlusXTrainingListVo onePlusXTrainingListVo : onePlusXTrainingListVos) {
            if (StrUtil.isNotEmpty(onePlusXTrainingListVo.getAttachFileJson())) {
                JSONArray jsonArray = JSONUtil.parseArray(onePlusXTrainingListVo.getAttachFileJson());
                List<AttachFileVo> attachFileVoList = jsonArray.toList(AttachFileVo.class);
                onePlusXTrainingListVo.setAttachFile(attachFileVoList);
            }

            if (StrUtil.isNotEmpty(onePlusXTrainingListVo.getStartTime()) && StrUtil.isNotEmpty(onePlusXTrainingListVo.getEndTime())) {
                DateTime startTime = DateUtil.parse(onePlusXTrainingListVo.getStartTime(), "yyyy-MM-dd HH:mm:ss");
                DateTime endTime = DateUtil.parse(onePlusXTrainingListVo.getEndTime(), "yyyy-MM-dd HH:mm:ss");

                if (DateUtil.isIn(DateUtil.date(), startTime, endTime)) {
                    onePlusXTrainingListVo.setStatus(1);
                } else {
                    if (DateUtil.compare(DateUtil.date(), startTime) > 0) {
                        onePlusXTrainingListVo.setStatus(2);
                    }
                    if (DateUtil.compare(DateUtil.date(), endTime) < 0) {
                        onePlusXTrainingListVo.setStatus(0);
                    }
                }
            }

            ArrayList<InvigilatorConfirmsVo> invigilatorConfirmsVos = new ArrayList<>();
            LambdaQueryWrapper<Invigilatorconfirm> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Invigilatorconfirm::getExamId, onePlusXTrainingListVo.getId());
            lqw.eq(Invigilatorconfirm::getStatus, 1);
            if (CollUtil.isNotEmpty(invigilatorconfirmService.list(lqw))) {
                List<Invigilatorconfirm> invigilatorconfirmList = invigilatorconfirmService.list(lqw);
                for (Invigilatorconfirm invigilatorconfirm : invigilatorconfirmList) {

                    InvigilatorConfirmsVo invigilatorConfirmsVo = new InvigilatorConfirmsVo();
                    invigilatorConfirmsVo.setId(invigilatorconfirm.getId());
                    invigilatorConfirmsVo.setRealname(invigilatorconfirm.getRealname());
                    invigilatorConfirmsVo.setTitle(invigilatorconfirm.getTitle());

                    invigilatorConfirmsVos.add(invigilatorConfirmsVo);
                }
            }
            onePlusXTrainingListVo.setInvigilatorConfirms(invigilatorConfirmsVos);
        }
        ArrayList<OnePlusXTrainingListVo> filterList = (ArrayList<OnePlusXTrainingListVo>) onePlusXTrainingListVos.stream().filter(x -> x.getStatus().equals(status)).collect(Collectors.toList());
        HashMap<String,Object> map = new HashMap<>();
        if (status != null) {
            map.put("rows",filterList);
            map.put("count",new PageInfo<>(filterList).getTotal());
//            return ResultT.success(filterList);
        } else {
            map.put("rows",onePlusXTrainingListVos);
            map.put("count",new PageInfo<>(onePlusXTrainingListVos).getTotal());
//            return ResultT.success(onePlusXTrainingListVos);
        }
        return ResultT.success(map);
    }

    @GetMapping("/detail")
    @ApiOperation("获取培训管理详情")
    public ResultT detail(String trainingId) {

        if (StrUtil.isEmpty(trainingId)) {
            return ResultT.fail("数据错误");
        }
        if (oneplusxtrainingService.getById(trainingId) == null) {
            return ResultT.fail("数据错误");
        }

        Oneplusxtraining oneplusxtraining = oneplusxtrainingService.getById(trainingId);
        OneplusXtrainingDeatilVo oneplusXtrainingDeatilVo = BeanUtil.copyProperties(oneplusxtraining, OneplusXtrainingDeatilVo.class, "attachFile");

        ArrayList<InvigilatorConfirmsVo> invigilatorConfirmsVos = new ArrayList<>();
        LambdaQueryWrapper<Invigilatorconfirm> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Invigilatorconfirm::getExamId, trainingId);
        if (CollUtil.isNotEmpty(invigilatorconfirmService.list(lqw))) {
            List<Invigilatorconfirm> invigilatorconfirmList = invigilatorconfirmService.list(lqw);
            for (Invigilatorconfirm invigilatorconfirm : invigilatorconfirmList) {

                InvigilatorConfirmsVo invigilatorConfirmsVo = new InvigilatorConfirmsVo();
                invigilatorConfirmsVo.setId(invigilatorconfirm.getId());
                invigilatorConfirmsVo.setRealname(invigilatorconfirm.getRealname());
                invigilatorConfirmsVo.setTitle(invigilatorconfirm.getTitle());
                invigilatorConfirmsVo.setStatus(invigilatorconfirm.getStatus());
                invigilatorConfirmsVo.setUserId(invigilatorconfirm.getUserId());

                invigilatorConfirmsVos.add(invigilatorConfirmsVo);
            }
        }

        String attachFileJson = oneplusxtraining.getAttachFile();
        List<AttachFileVo> attachFileVoList = JSONUtil.toList(attachFileJson, AttachFileVo.class);


        Certnum certnum = new Certnum();
        if (StrUtil.isNotEmpty(oneplusxtraining.getCertNumPrefix())) {
            LambdaQueryWrapper<Certnum> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Certnum::getPrefix, oneplusxtraining.getCertNumPrefix());
            List<Certnum> list = certnumService.list(lqww);
            if (CollUtil.isNotEmpty(list)) {
                certnum = list.get(0);
                oneplusXtrainingDeatilVo.setLevel(certnum.getLevel());
                oneplusXtrainingDeatilVo.setCertTitle(certnum.getTitle());
                oneplusXtrainingDeatilVo.setCertType(certnum.getCertType());
            }
        }


        oneplusXtrainingDeatilVo.setInvigilatorConfirms(invigilatorConfirmsVos);
        oneplusXtrainingDeatilVo.setAttachFile(attachFileVoList);
//        List<OneplusXtrainingDeatilVo> data = new ArrayList<>();
//        data.add(oneplusXtrainingDeatilVo);
        return ResultT.success(oneplusXtrainingDeatilVo);
    }


    @PostMapping("/stayAtTop")
    @ApiOperation("置顶与取消置顶")
    public ResultT stayAtTop(@RequestBody OnePlusXTrainingStayAtTopVo onePlusXTrainingStayAtTopVo) {

        String trainingId = onePlusXTrainingStayAtTopVo.getTrainingId();
        Integer stayAtTop = onePlusXTrainingStayAtTopVo.getStayAtTop();


        if (oneplusxtrainingService.getById(trainingId) == null) {
            return ResultT.fail("数据错误");
        }
        if (stayAtTop == null) {
            return ResultT.fail("数据错误");
        }

        Oneplusxtraining oneplusxtraining = oneplusxtrainingService.getById(trainingId);
        oneplusxtraining.setStayAtTop(stayAtTop);
        oneplusxtraining.setSortTime(DateUtil.now());

        boolean update = oneplusxtrainingService.updateById(oneplusxtraining);
        if (update) {

            if (stayAtTop == 1) {
                return ResultT.success("置顶成功");
            }

            if (stayAtTop == 0) {
                return ResultT.success("取消置顶成功");
            }
        }
        return ResultT.fail("操作失败");
    }


    @PostMapping("/delete")
    @ApiOperation("删除培训")
    public ResultT delete(@RequestBody OnePlusXTrainingIdVo onePlusXTrainingIdVo) {

        String trainingId = onePlusXTrainingIdVo.getTrainingId();

        if (oneplusxtrainingService.getById(trainingId) == null) {
            return ResultT.fail("数据错误");
        }

        boolean remove = oneplusxtrainingService.removeById(trainingId);

        if (remove) {
            return ResultT.success("删除成功");
        } else {
            return ResultT.fail("删除失败");
        }
    }


    @PostMapping("/addTraining")
    @ApiOperation("新增培训")
    public ResultT addTraining(@RequestBody AddTrainingVo addTrainingVo) {
        Oneplusxtraining oneplusxtraining = BeanUtil.copyProperties(addTrainingVo, Oneplusxtraining.class, "attachFile");

        oneplusxtraining.setId(IdUtil.randomUUID());
        oneplusxtraining.setCreateTime(DateUtil.now());
        oneplusxtraining.setSortTime(DateUtil.now());
        JSON json = JSONUtil.parse(addTrainingVo.getAttachFile());
        String attachFile = JSONUtil.toJsonStr(json);
        oneplusxtraining.setAttachFile(attachFile);

        boolean save = oneplusxtrainingService.save(oneplusxtraining);

        if (save) {
            return ResultT.success("新增成功");
        } else {
            return ResultT.fail("新增失败");
        }
    }

    @PostMapping("/update")
    @ApiOperation("更新培训")
    public ResultT update(@RequestBody UpdateOnePlusXTrainingVo updateOnePlusXTrainingVo) {

        if (oneplusxtrainingService.getById(updateOnePlusXTrainingVo.getTrainingId()) == null) {
            return ResultT.fail("数据错误");
        }
        Oneplusxtraining oneplusxtraining = BeanUtil.copyProperties(updateOnePlusXTrainingVo, Oneplusxtraining.class, "attachFile");


        JSON json = JSONUtil.parse(updateOnePlusXTrainingVo.getAttachFile());
        String attachFile = JSONUtil.toJsonStr(json);


        oneplusxtraining.setId(updateOnePlusXTrainingVo.getTrainingId());
        oneplusxtraining.setAttachFile(attachFile);
        boolean update = oneplusxtrainingService.updateById(oneplusxtraining);

        if (update) {
            return ResultT.success("更新成功");
        } else {
            return ResultT.fail("更新失败");
        }
    }

    @GetMapping("/trainerList")
    @ApiOperation("培训人员列表")
    public ResultT trainerList(String trainingId, Integer status, String keyword) {

        QueryWrapper<GetTrainerListBo> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(trainingId)) {
            qw.eq("trainerapply.trainingId", trainingId);
        }
        if (StrUtil.isNotEmpty(keyword)) {
            qw.like("creator.name", keyword);
        }
        if (status != null) {
            qw.eq("trainerapply.status", status);
        }
        qw.orderByDesc("trainerapply.id");
        List<GetTrainerListBo> trainerapplyMapperListBos = trainerapplyMapper.getListBo(qw);
        ArrayList<TrainerApplyVo> trainerApplyVos = new ArrayList<>();

        for (GetTrainerListBo trainerapplyMapperListBo : trainerapplyMapperListBos) {
            TrainerApplyVo trainerApplyVo = BeanUtil.copyProperties(trainerapplyMapperListBo, TrainerApplyVo.class, "attachFile");

            if (StrUtil.isNotEmpty(trainerapplyMapperListBo.getAttachFile())) {

                JSONArray jsonArray = new JSONArray(trainerapplyMapperListBo.getAttachFile());
                List<AttachFileVo> attachFileVoList = JSONUtil.toList(jsonArray, AttachFileVo.class);
                trainerApplyVo.setAttachFile(attachFileVoList);
            }

            PublisherVo publisherVo = new PublisherVo();
            publisherVo.setId(trainerapplyMapperListBo.getPublisherId());
            publisherVo.setName(trainerapplyMapperListBo.getPublisherName());
            trainerApplyVo.setPublisher(publisherVo);

            User creator = new User();
            creator.setId(trainerapplyMapperListBo.getCreatorId());
            creator.setAccount(trainerapplyMapperListBo.getCreatorAccount());
            creator.setGender(trainerapplyMapperListBo.getCreatorGender());
            creator.setIdCardNum(trainerapplyMapperListBo.getCreatorIdCardNum());
            creator.setInstituteName(trainerapplyMapperListBo.getCreatorInstituteName());
            creator.setName(trainerapplyMapperListBo.getCreatorName());
            creator.setRealname(trainerapplyMapperListBo.getCreatorRealname());
            creator.setTelephone(trainerapplyMapperListBo.getCreatorTelephone());
            trainerApplyVo.setCreator(creator);

            trainerApplyVos.add(trainerApplyVo);

        }

        PageInfo<TrainerApplyVo> info = new PageInfo<>();
        info.setList(trainerApplyVos);
        info.setTotal(new PageInfo<>(trainerapplyMapperListBos).getTotal());

        return ResultT.success(info);
    }


    @PostMapping("/updateStatus")
    @ApiOperation("更改培训人员状态")
    public ResultT updateStatus(@RequestBody UpdateStatuVo updateStatuVo) {
        Integer applyId = updateStatuVo.getApplyId();

        if (trainerapplyService.getById(applyId) == null) {
            return ResultT.fail("数据错误");
        }

        Trainerapply trainerapply = trainerapplyService.getById(applyId);
        trainerapply.setStatus(updateStatuVo.getStatus());
        boolean update = trainerapplyService.updateById(trainerapply);

        if (update) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }


    @PostMapping("/deleteTrainerApply")
    @ApiOperation("删除报名人员")
    public ResultT deleteTrainerApply(@RequestBody ApplyIdVo applyIdVo) {
        Integer applyId = applyIdVo.getApplyId();

        if (trainerapplyService.getById(applyId) == null) {
            return ResultT.fail("数据错误");
        }

        boolean remove = trainerapplyService.removeById(applyId);

        if (remove) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }

    }

    @PostMapping("/deleteCert")
    @ApiOperation("删除证书")
    public ResultT deleteCert(@RequestBody CertIdVo certIdVo) {
        List<Integer> certId = certIdVo.getCertId();
        try {
          if(CollUtil.isNotEmpty(certId)){
              for (Integer integer : certId) {
                  certificateService.removeById(integer);
              }
          }
            return ResultT.success("操作成功");
        }catch (Exception e){
            return ResultT.fail("操作失败");
        }
    }

}
